package com.d3works.apps.sale.service;

import com.d3works.apps.base.db.Product;
import com.d3works.apps.base.db.Unit;
import com.d3works.apps.base.db.repo.ProductRepository;
import com.d3works.apps.base.service.ProductCompanyService;
import com.d3works.apps.sale.db.Pack;
import com.d3works.apps.sale.db.PackLine;
import com.d3works.exception.D3worksException;
import com.google.inject.Inject;
import java.math.BigDecimal;

public class PackLineServiceImpl implements PackLineService {

  protected ProductRepository productRepository;
  protected ProductCompanyService productCompanyService;

  @Inject
  public PackLineServiceImpl(
      ProductRepository productRepository, ProductCompanyService productCompanyService) {
    this.productRepository = productRepository;
    this.productCompanyService = productCompanyService;
  }

  @Override
  public PackLine resetProductInformation(PackLine packLine) {

    packLine.setProductName(null);
    packLine.setPrice(null);
    packLine.setUnit(null);
    packLine.setQuantity(BigDecimal.ZERO);
    return packLine;
  }

  @Override
  public PackLine computeProductInformation(Pack pack, PackLine packLine) throws D3worksException {
    Product product = packLine.getProduct();
    product = productRepository.find(product.getId());

    packLine.setProductName(product.getName());
    packLine.setUnit(this.getSaleUnit(product));
    packLine.setPrice(this.getUnitPrice(packLine, pack));
    return packLine;
  }

  private Unit getSaleUnit(Product product) {
    Unit unit = product.getSalesUnit();
    if (unit == null) {
      unit = product.getUnit();
    }
    return unit;
  }

  private BigDecimal getUnitPrice(PackLine packLine, Pack pack) throws D3worksException {
    return (BigDecimal)
        productCompanyService.get(packLine.getProduct(), "salePrice", pack.getCompany());
  }
}
